<template>
  <div class="auto pc:max-w-[1200px] mobile:px-10">
    <Dialog
      v-model:visible="visible"
      modal
      :header="i18nStore.translate('举报')"
      :style="{ width: '45rem' }"
    >
      <div class="flex">
        <div>{{ i18nStore.translate('举报理由') }}：</div>
        <div class="flex flex-wrap gap-3">
          <div class="flex align-items-center">
            <RadioButton
              v-model="reportForm.reportType"
              inputId="ingredient1"
              name="pizza"
              :value="1"
            />
            <label for="ingredient1" class="ml-2">{{
              i18nStore.translate('淫秽色情')
            }}</label>
          </div>
          <div class="flex align-items-center">
            <RadioButton
              v-model="reportForm.reportType"
              inputId="ingredient2"
              name="pizza"
              :value="2"
            />
            <label for="ingredient2" class="ml-2">{{
              i18nStore.translate('血腥暴力')
            }}</label>
          </div>
          <div class="flex align-items-center">
            <RadioButton
              v-model="reportForm.reportType"
              inputId="ingredient3"
              name="pizza"
              :value="3"
            />
            <label for="ingredient3" class="ml-2">{{
              i18nStore.translate('敏感政治')
            }}</label>
          </div>
          <div class="flex align-items-center">
            <RadioButton
              v-model="reportForm.reportType"
              inputId="ingredient4"
              name="pizza"
              :value="4"
            />
            <label for="ingredient4" class="ml-2">{{
              i18nStore.translate('诈骗')
            }}</label>
          </div>
          <div class="flex align-items-center">
            <RadioButton
              v-model="reportForm.reportType"
              inputId="ingredient4"
              name="pizza"
              :value="5"
            />
            <label for="ingredient4" class="ml-2">{{
              i18nStore.translate('其他违规违法行为')
            }}</label>
          </div>
        </div>
      </div>

      <div class="flex my-3">
        <div>{{ i18nStore.translate('问题描述') }}：</div>
        <Textarea
          v-model="reportForm.description"
          rows="5"
          cols="30"
          class="border-[1px] border-[#cdcbcb]"
        />
      </div>

      <div class="flex my-3">
        <div>{{ i18nStore.translate('您的姓名') }}：</div>
        <InputText
          type="text"
          v-model="reportForm.informerName"
          class="border-[1px] border-[#cdcbcb]"
        />
      </div>

      <div class="flex my-3">
        <div>{{ i18nStore.translate('您的身份证号码') }}：</div>
        <InputText
          type="text"
          v-model="reportForm.informerIdCard"
          class="border-[1px] border-[#cdcbcb]"
        />
      </div>

      <div class="w-full flex justify-around my-5">
        <MyButton
          class="bg-[#00e0a9] flex-1 text-center h-[35px] leading-[35px] rounded-xl mr-1 font-bold text-white"
          @click="visible = false"
        >
          {{ i18nStore.translate('cancel') }}
        </MyButton>
        <MyButton
          class="bg-[#00e1d9] flex-1 text-center h-[35px] leading-[35px] rounded-xl ml-1 font-bold text-white"
          @click="handleReport"
        >
          {{ i18nStore.translate('confirm') }}
        </MyButton>
      </div>
    </Dialog>
    <Nav />
    <ProgressBar
      mode="indeterminate"
      style="height: 6px"
      v-if="loading"
    ></ProgressBar>

    <div class="pc:hidden w-full flex flex-row-reverse">
      <MyButton
        class="ml-3 mx-4 my-1 border-[1px] border-[#cdcbcb] rounded-xl text-white bg-[#0d53ff] px-4 py-2 font-bold"
        @click="saveToMyClouds"
        ><i class="pi pi-reply" />
        {{ i18nStore.translate('保存到云盘') }}</MyButton
      >
      <MyButton
        class="mx-4 my-1 border-[1px] border-[#cdcbcb] rounded-xl px-4 py-2 font-bold"
        @click="downloadFile"
        ><i class="pi pi-download" />
        {{ i18nStore.translate('下载') }}</MyButton
      >
    </div>

    <div
      class="w-full h-[600px] pc:border-[1px] border-[#cdcbcb] pc:px-10 pc:py-10 pc:rounded-2xl"
    >
      <div class="flex items-center">
        <div class="flex-1">
          <div class="flex items-center">
            <div>
              <div class="relative mx-auto">
                <div
                  v-if="data.isFolder"
                  class="mt-3 mb-5 inline-block scale-150 transform lg:mt-2 lg:mb-8"
                >
                  <div class="svg-color-theme">
                    <SvgIcon
                      name="folder"
                      :style="{ width: '53px', height: '52px' }"
                      iconClass="svg-color-theme"
                    />
                  </div>
                </div>

                <div
                  v-else-if="data.type === 'image'"
                  class="relative mb-4 inline-block h-24 w-28 lg:h-28 lg:w-36"
                >
                  <img
                    :src="data.previewUrl"
                    alt=""
                    loading="lazy"
                    class="h-full w-full rounded-lg object-cover shadow-lg"
                  />
                </div>
                <div
                  v-else-if="data.type === 'video'"
                  class="relative mb-4 inline-block h-24 w-28 lg:h-28 lg:w-36"
                >
                  <video
                    :src="data.previewUrl"
                    class="h-full w-full rounded-lg object-cover shadow-lg"
                    loop
                    muted
                    @loadeddata="
                      (e) => {
                        e.target.volume = 0;
                        e.target.play();
                      }
                    "
                  />
                </div>
                <div
                  v-else
                  class="flex items-center justify-center z-0 mt-5 mb-10 scale-125 transform lg:mb-12 lg:mt-6 lg:scale-150"
                >
                  <span
                    class="text-theme-color absolute z-[5] mx-auto mt-1 inline-block w-7 overflow-hidden text-ellipsis text-center text-[9px] font-semibold"
                  >
                    {{ data.type }}
                  </span>
                  <SvgIcon
                    name="file"
                    svgClass="vue-feather dark:text-gray-800 text-gray-100 "
                    :style="{ width: '38px', height: '51px' }"
                    iconClass="svg-color-theme"
                  />
                </div>
              </div>
            </div>
            <div class="flex flex-col ml-8 font-bold text-lg">
              <div>{{ data.fileName }}</div>
              <div>
                {{
                  i18nStore.translate('expiration_time') +
                  '：' +
                  parseTime(data.expireTime)
                }}
                <span
                  class="text-[12px] text-[#0d53ff] cursor-pointer"
                  @click="visible = true"
                >
                  {{ i18nStore.translate('举报') }}</span
                >
              </div>
            </div>
          </div>
        </div>
        <div class="flex-1 flex justify-end text-xl mobile:hidden">
          <MyButton
            class="px-4 py-2 cursor-pointer border border-[#cdcbcb] rounded-xl mr-4"
            @click="downloadFile"
          >
            <i class="pi pi-download" /><span class="font-bold">
              {{ i18nStore.translate('下载') }}</span
            >
          </MyButton>
          <MyButton
            class="px-4 py-2 cursor-pointer rounded-xl text-white bg-[#0d53ff]"
            @click="saveToMyClouds"
          >
            <i class="pi pi-reply" /><span class="font-bold">
              {{ i18nStore.translate('保存到云盘') }}</span
            >
          </MyButton>
        </div>
      </div>

      <div class="w-full border-b-[1px] border-[#cdcbcb] mt-5"></div>

      <div class="font-bold my-5">
        <i
          class="pi pi-angle-left cursor-pointer"
          v-if="prevFolders.length"
          @click="goBack"
        ></i>
        {{ i18nStore.translate('全部文件') }}
      </div>

      <div class="w-full overflow-y-auto h-[350px]">
        <div class="flex">
          <div class="w-[35%] flex items-center">
            <Checkbox
              v-model="checkedAll"
              inputId="ingredient1"
              :binary="true"
              @change="handleCheckAll"
            />
            <label
              for="ingredient1"
              class="text-[#5CD6C8] text-[18px] cursor-pointer font-bold ml-2"
              >All</label
            >
          </div>
          <div
            class="text-[#5CD6C8] text-[16px] cursor-pointer font-bold w-[35%] text-center"
          >
            {{ i18nStore.translate('文件大小') }}
          </div>
          <div
            class="text-[#5CD6C8] text-[16px] cursor-pointer font-bold w-[30%] text-center"
          >
            {{ i18nStore.translate('创建时间')
            }}<svg
              @click="sort"
              t="1730545465565"
              class="icon inline-block"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="9949"
              width="40"
              height="40"
            >
              <path
                d="M581.6 714.72V217.28a14.4 14.4 0 0 1 14.56-14.56h34.72a14.56 14.56 0 0 1 14.72 14.56v353.6a14.56 14.56 0 0 0 14.56 14.56h64A14.56 14.56 0 0 1 736 608l-128 176a14.4 14.4 0 0 1-26.24-8.48z m-84.8-405.44v497.44a14.56 14.56 0 0 1-14.56 14.56H448a14.4 14.4 0 0 1-14.56-14.56v-353.6a14.56 14.56 0 0 0-14.56-14.56h-64a14.56 14.56 0 0 1-12.64-22.56l128-176a14.56 14.56 0 0 1 26.4 8.48z"
                fill="#4592D8"
                p-id="9950"
              ></path>
            </svg>
          </div>
        </div>

        <div
          class="flex my-1 hover:bg-[#f2f2f2] py-4"
          v-for="item in dataList"
          :key="item"
          @dblclick="
            () => {
              item.isFolder ? getFolderDetail(item.fileId) : '';
            }
          "
        >
          <div class="w-[35%] flex">
            <Checkbox
              v-model="checkedItems"
              name="pizza"
              :value="item"
              @change.stop="handleCheck"
            />

            <div class="flex items-center ml-2">
              <div class="flex-1">
                <div class="flex items-center">
                  <div>
                    <div class="relative mx-auto">
                      <div
                        v-if="item.isFolder"
                        class="inline-block scale-150 transform"
                      >
                        <div class="svg-color-theme">
                          <SvgIcon
                            name="folder"
                            :style="{ width: '1.5rem', height: '1.5rem' }"
                            iconClass="svg-color-theme"
                          />
                        </div>
                      </div>
                      <div
                        v-else
                        class="flex items-center justify-center z-0 scale-125 transform lg:scale-150"
                      >
                        <span
                          class="text-theme-color absolute z-[5] mx-auto mt-1 inline-block w-7 overflow-hidden text-ellipsis text-center text-[9px] font-semibold"
                        >
                          {{
                            item.isFolder
                              ? item.fileName.slice(0, -1)
                              : item.fileName.split('.').pop()
                          }}
                        </span>
                        <SvgIcon
                          name="file"
                          svgClass="vue-feather dark:text-gray-800 text-gray-100 "
                          :style="{ width: '1.5rem', height: '1.5rem' }"
                          iconClass="svg-color-theme"
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <label
              class="ml-2 text-[#3c3c3c] cursor-pointer overflow-hidden text-ellipsis text-nowrap"
              >{{
                item.isFolder ? item.fileName.slice(0, -1) : item.fileName
              }}</label
            >
          </div>
          <div
            class="text-[#3c3c3c] w-[35%] overflow-hidden text-ellipsis text-nowrap text-center"
          >
            {{ item.isFolder ? '-' : formatFileSize(item.fileSize) }}
          </div>
          <div class="text-[#3c3c3c] text-[16px] w-[30%] text-center">
            {{ timestampToTime(item.fileCreateTime) }}
          </div>
        </div>
      </div>
    </div>

    <div class="fixed left-0 bottom-0 w-full">
      <div class="text-sm font-bold text-center">
        {{ i18nStore.translate('版权声明') + i18nStore.translate('声明') }}
      </div>
      <div class="text-sm font-bold text-center">
        {{ i18nStore.translate('郑州矩阵软件科技有限公司版权所有') }}
      </div>
    </div>
  </div>
</template>
<script setup>
import { useFlagStore, useToastStore, useI18nStore } from '@/stores';
import {
  shareFileDetail,
  getDownloadUrl,
  getDownTentacleUrl,
  transferToPersonal,
  reportAbuse
} from '@/apis/file';
import logo from '@/assets/icons/logo.svg';
const toastStore = useToastStore();
const i18nStore = useI18nStore();
const route = useRoute();
const router = useRouter();
const id = atob(route.params.id);
const code = atob(route.params.code) == '-1' ? '' : atob(route.params.code);
const sortType = ref(1);
const prevFolders = ref([]);

const data = ref({});
const dataList = ref([]);
const checkedAll = ref(false);
const checkedItems = ref([]);
const timer = ref(null);
const visible = ref(false);
const reportForm = ref({
  reportType: 1,
  description: '',
  informerName: '',
  informerIdCard: ''
});

const handleCheckAll = () => {
  checkedItems.value = checkedAll.value ? dataList.value : [];
};

const handleCheck = () => {
  if (checkedItems.value.length === dataList.value.length) {
    checkedAll.value = true;
  } else {
    checkedAll.value = false;
  }
};

const goBack = () => {
  prevFolders.value.pop();
  if (prevFolders.value.length) {
    getFolderDetail(prevFolders.value[prevFolders.value.length - 1], true);
  } else {
    getFileDetail();
  }
};

function getFolderDetail(fileId, isBack = false) {
  checkedItems.value = [];
  !isBack ? prevFolders.value.push(fileId) : '';
  shareFileDetail({ id, code, fileId }).then((res) => {
    checkedItems.value = res.data.children;
    checkedAll.value = true;
    dataList.value = res.data.children;
    console.log(prevFolders.value);
  });
}

function getFileDetail() {
  shareFileDetail({ id, code }).then((res) => {
    if (res.code !== 0) {
      toastStore.showToast({
        severity: 'error',
        summary: 'Error Message',
        detail: res.msg,
        life: 999999,
        group: 'upload_failed'
      });
      setTimeout(() => {
        window.location.replace('https://okpan.com/');
      }, 1000);
    }
    const fileType = getFileType('.' + res.data.fileName.split('.').pop());
    const type =
      fileType.type === 'image'
        ? 'image'
        : fileType.extension === 'unknown_type'
        ? ''
        : fileType.extension;
    data.value = { ...res.data, type };
    if (data.value.isFolder) {
      checkedItems.value = res.data.children;
      checkedAll.value = true;
      data.value.fileName = data.value.fileName.slice(0, -1);
      dataList.value = res.data.children;
    } else {
      dataList.value = [res.data];
      checkedAll.value = true;
      checkedItems.value = [res.data];
    }
    document.title = data.value.fileName + ' - OK云盘 - 您的文件存储解决方案';
  });
}

const loading = ref(false);

function downloadFile() {
  if (!checkedItems.value.length) {
    toastStore.showToast({
      severity: 'error',
      summary: i18nStore.translate('请选择文件'),
      detail: i18nStore.translate('请选择文件后再下载'),
      life: 2000,
      group: 'upload_success'
    });
    return;
  }

  if (data.value.isFolder) {
    getDownloadUrl({
      code,
      id: data.value.id,
      fileIds: checkedItems.value.map((item) => item.fileId)
    }).then((res) => {
      if (res.code === 0) {
        loading.value = true;
        timer.value = setInterval(() => {
          getDownTentacleUrl({ jobId: res.data }).then((res) => {
            if (res.code === 0) {
              const A = document.createElement('a');
              A.href = res.data;
              A.download = data.value.fileName;
              A.click();
              loading.value = false;
              clearInterval(timer.value);
            }
            if (res.code === 512) {
              loading.value = false;
              toastStore.showToast({
                severity: 'error',
                summary: 'Error Message',
                detail: res.msg,
                life: 999999,
                group: 'upload_failed'
              });
              clearInterval(timer.value);
            }
          });
        }, 3000);
      } else {
        loading.value = false;
        toastStore.showToast({
          severity: 'error',
          summary: 'Error Message',
          detail: res.msg,
          life: 999999,
          group: 'upload_failed'
        });
        clearInterval(timer.value);
        setTimeout(() => {
          window.location.href = 'https://okpan.com/';
        }, 1500);
      }
    });
  } else {
    loading.value = true;
    getDownloadUrl({
      code,
      id: data.value.id
    }).then((res) => {
      if (res.code === 0) {
        const A = document.createElement('a');
        A.href = res.data;
        A.download = data.value.fileName;
        A.click();
      } else {
        toastStore.showToast({
          severity: 'error',
          summary: 'Error Message',
          detail: res.msg,
          life: 999999,
          group: 'upload_failed'
        });
      }
      loading.value = false;
    });
  }
}

const flagStore = useFlagStore();

const validateNameAndId = (name, idCard) => {
  const nameRegex = /^[\u4e00-\u9fa5A-Za-z\s]{2,20}$/;
  const idCardRegex = /^(?:\d{15}|\d{17}[\dX])$/;
  const isNameValid = nameRegex.test(name);
  const isIdValid = idCardRegex.test(idCard);
  return isNameValid && isIdValid ? 1 : 0;
};

const handleReport = () => {
  if (
    validateNameAndId(
      reportForm.value.informerName,
      reportForm.value.informerIdCard
    )
  ) {
    reportAbuse({
      id: data.value.id,
      fileId: data.value.fileId,
      ...reportForm.value
    }).then((res) => {
      if (res.code === 0) {
        toastStore.showToast({
          severity: 'success',
          summary: 'Success Message',
          detail: res.msg
        });
      } else {
        toastStore.showToast({
          severity: 'error',
          summary: res.data,
          life: 2000,
          group: 'upload_success'
        });
      }
      visible.value = false;
    });
  } else {
    toastStore.showToast({
      severity: 'error',
      summary: i18nStore.translate('请填写正确的身份信息'),
      life: 2000,
      group: 'upload_success'
    });
    visible.value = false;
  }
};
import { useUserInfoStore } from '@/stores';
const userInfoStore = useUserInfoStore();
const { okCloudDiskToken } = storeToRefs(userInfoStore);

const saveToMyClouds = () => {
  if (!okCloudDiskToken.value) {
    router.push('/login');
  } else {
    showTreePopup({
      isMove: 0,
      pid: data.valuefileId,
      ids: checkedItems.value.map((item) => item.fileId)
    });
  }
};

const timestampToTime = (timestamp) => {
  const date = new Date(timestamp);
  const Y = date.getFullYear() + '-';
  const M =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + '-';
  const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  const h =
    (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  const m =
    (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
    ':';
  const s =
    date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return Y + M + D + h + m + s;
};

const sort = () => {
  if (sortType.value === 1) {
    dataList.value.sort((a, b) => b.fileCreateTime - a.fileCreateTime);
    sortType.value = 2;
  } else {
    dataList.value.sort((a, b) => a.fileCreateTime - b.fileCreateTime);
    sortType.value = 1;
  }
};

onMounted(() => {
  getFileDetail();
});
</script>
<style lang="scss" scoped></style>
